package com.order.controller.user;


import com.order.context.BaseContext;
import com.order.dto.ShoppingCartDto;
import com.order.entity.ShoppingCart;
import com.order.result.Result;
import com.order.service.CartService;
import com.order.service.OrderService;
import com.order.vo.ShoppingCartVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "用户-购物车相关接口")
@Slf4j
@RequestMapping("/user/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @GetMapping
    @ApiOperation("查看购物车")
    public Result<ShoppingCartVo> search(){
        List<ShoppingCart> shoppingCarts = cartService.search(BaseContext.getCurrentId());
        ShoppingCartVo shoppingCartVo = ShoppingCartVo.builder()
                .num(shoppingCarts.size())
                .shoppingCarts(shoppingCarts)
                .build();
        return Result.success(shoppingCartVo);
    }

    @PostMapping("/add")
    @ApiOperation("添加购物车")
    public Result add(@RequestBody ShoppingCartDto shoppingCartDto){
        ShoppingCart cart = ShoppingCart.builder()
                .productId(shoppingCartDto.getProductId())
                .quantity(shoppingCartDto.getQuantity())
                .amount(shoppingCartDto.getAmount())
                .build();
        cartService.add(cart);

        return Result.success();
    }

    @PostMapping("/update")
    @ApiOperation("更新购物车")
    public Result update(@RequestBody ShoppingCartDto shoppingCartDto){
        ShoppingCart cart = ShoppingCart.builder()
                .id(shoppingCartDto.getId())
                .productId(shoppingCartDto.getProductId())
                .quantity(shoppingCartDto.getQuantity())
                .amount(shoppingCartDto.getAmount())
                .build();
        cartService.update(cart);

        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("删除购物车商品")
    public Result delete(@RequestBody List<Long> ids){
        cartService.delete(ids);
        return Result.success();
    }

    @DeleteMapping("/all")
    @ApiOperation("结算")
    public Result deleteAll(){

        orderService.submit();

        return Result.success();
    }

}
